package demo.client;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.core.Pcaps;

import demo.api.EthernetService;
import demo.api.IcmpEchoSession;
import demo.impl.ethernet.EthernetServiceImpl;
import demo.impl.icmp.IcmpServiceImpl;
import demo.impl.ipv4.IPv4ServiceImpl;

/**
 * 演示客户端
 * 
 * @author caohj
 * @date 2017年8月6日
 */
public class PingDemo {
	public static void main(String[] args) throws Exception {
		System.out.print("输入域名或者ip：");
		String host = new Scanner(System.in).nextLine();
		EthernetService ethernet = null;
		try {
			Inet4Address destip = (Inet4Address) Inet4Address.getByName(host);
			PcapNetworkInterface nif = Pcaps.getDevByAddress(InetAddress.getLocalHost());
			ethernet = new EthernetServiceImpl(nif);
			ethernet.setFilter("(not broadcast) and (not tcp) and (not host 239.255.255.250) and (not port 53)");
			IPv4ServiceImpl ipv4 = new IPv4ServiceImpl(ethernet);
			IcmpServiceImpl icmp = new IcmpServiceImpl(ipv4);
			// icmp.setLogPacketOption(true);

			IcmpEchoSession session = icmp.createEchoSession();
			List<IcmpEchoSession.EchoReplyInfo> replyInfos = new ArrayList<IcmpEchoSession.EchoReplyInfo>(4);
			System.out.println("正在 ping " + destip.getHostName() + " [" + destip.getHostAddress() + "]：");

			for (int i = 0; i < 4; i++) {
				try {
					IcmpEchoSession.EchoReplyInfo reply = session.sendEcho(destip, 5);
					System.out.println("来自 " + destip.getHostAddress() + " 的回复：时间=" + reply.getDurationInMilliSecond()
							+ "ms TTL=" + reply.getTTL());
					replyInfos.add(reply);
				} catch (TimeoutException e) {
					System.out.println("请求超时。");
				}
			}
			System.out.println(destip.getHostAddress() + " 的 Ping 统计信息：");
			int lost = (4 - replyInfos.size());
			System.out.println("\t数据包：已发送 = 4, 已接收 = " + replyInfos.size() + "，丢失 = " + lost + " （"
					+ (int) (lost / 4 * 100) + "%） 丢失.");
		} catch (UnknownHostException e) {
			System.out.println("Ping 请求找不到主机 " + host + "。请检查该名称，然后重试。");
		} finally {
			if (ethernet != null) {
				ethernet.close();
			}
		}
	}
}
